import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:xiaofanshu_flutter/components/custom_guide_widget.dart';

/// 引导服务 - 管理应用的新手引导功能
class GuideService {
  static const String _keyFirstLaunch = 'is_first_launch';
  static const String _keyGuideCompleted = 'guide_completed';
  
  // 各个页面的引导完成状态
  static const String _keyHomeGuideCompleted = 'home_guide_completed';
  static const String _keyStoryMapGuideCompleted = 'story_map_guide_completed';
  static const String _keyMessageGuideCompleted = 'message_guide_completed';
  static const String _keyMineGuideCompleted = 'mine_guide_completed';

  /// 检查是否是首次启动
  static Future<bool> isFirstLaunch() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getBool(_keyFirstLaunch) ?? true;
  }

  /// 设置已经启动过
  static Future<void> setNotFirstLaunch() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool(_keyFirstLaunch, false);
  }

  /// 检查引导是否已完成
  static Future<bool> isGuideCompleted() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getBool(_keyGuideCompleted) ?? false;
  }

  /// 设置引导已完成
  static Future<void> setGuideCompleted() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool(_keyGuideCompleted, true);
    await prefs.setBool(_keyHomeGuideCompleted, true);
    await prefs.setBool(_keyStoryMapGuideCompleted, true);
    await prefs.setBool(_keyMessageGuideCompleted, true);
    await prefs.setBool(_keyMineGuideCompleted, true);
  }

  /// 重置引导状态（用于测试）
  static Future<void> resetGuide() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool(_keyFirstLaunch, true);
    await prefs.setBool(_keyGuideCompleted, false);
    await prefs.setBool(_keyHomeGuideCompleted, false);
    await prefs.setBool(_keyStoryMapGuideCompleted, false);
    await prefs.setBool(_keyMessageGuideCompleted, false);
    await prefs.setBool(_keyMineGuideCompleted, false);
  }

  /// 检查首页引导是否完成
  static Future<bool> isHomeGuideCompleted() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getBool(_keyHomeGuideCompleted) ?? false;
  }

  /// 设置首页引导已完成
  static Future<void> setHomeGuideCompleted() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool(_keyHomeGuideCompleted, true);
  }

  /// 重置首页引导状态（用于重新显示引导）
  static Future<void> resetHomeGuideCompleted() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool(_keyHomeGuideCompleted, false);
  }

  /// 检查故事地图引导是否完成
  static Future<bool> isStoryMapGuideCompleted() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getBool(_keyStoryMapGuideCompleted) ?? false;
  }

  /// 设置故事地图引导已完成
  static Future<void> setStoryMapGuideCompleted() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool(_keyStoryMapGuideCompleted, true);
  }

  /// 检查消息页引导是否完成
  static Future<bool> isMessageGuideCompleted() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getBool(_keyMessageGuideCompleted) ?? false;
  }

  /// 设置消息页引导已完成
  static Future<void> setMessageGuideCompleted() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool(_keyMessageGuideCompleted, true);
  }

  /// 检查我的页面引导是否完成
  static Future<bool> isMineGuideCompleted() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getBool(_keyMineGuideCompleted) ?? false;
  }

  /// 设置我的页面引导已完成
  static Future<void> setMineGuideCompleted() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool(_keyMineGuideCompleted, true);
  }

  /// 创建引导步骤（使用自定义组件）
  static GuideStep createGuideStep({
    GlobalKey? targetKey,
    required String title,
    required String description,
    IconData? icon,
    Offset? contentPosition,
  }) {
    // 如果提供了 targetKey，获取其位置
    Rect? targetRect;
    if (targetKey != null) {
      targetRect = getWidgetBounds(targetKey);
    }

    // 计算内容位置（如果没有指定）
    Offset finalContentPosition = contentPosition ?? const Offset(20, 100);
    if (targetRect != null && contentPosition == null) {
      // 自动计算位置：在目标下方居中
      final screenWidth = Get.width;
      final contentWidth = screenWidth * 0.8;
      finalContentPosition = Offset(
        (screenWidth - contentWidth) / 2,
        targetRect.bottom + 20,
      );
    }

    return GuideStep(
      title: title,
      description: description,
      icon: icon,
      contentPosition: finalContentPosition,
      targetRect: targetRect,
    );
  }

  /// 显示引导
  static void showGuide({
    required BuildContext context,
    required List<GuideStep> steps,
    VoidCallback? onFinish,
    VoidCallback? onSkip,
  }) {
    showCustomGuide(
      context,
      steps: steps,
      onFinish: () {
        onFinish?.call();
      },
      onSkip: () {
        onSkip?.call();
      },
    );
  }
}

/// 引导控制器
class GuideController extends GetxController {
  // 当前引导进度
  final RxInt currentGuideStep = 0.obs;
  
  // 是否正在显示引导
  final RxBool isShowingGuide = false.obs;
  
  // ========== 所有页面的触发器 ==========
  final RxBool shouldShowIndexGuide = false.obs;
  final RxBool shouldShowMapGuide = false.obs;
  final RxBool shouldShowMessageGuide = false.obs;
  final RxBool shouldShowMineGuide = false.obs;
  // ====================================

  /// 开始引导流程
  Future<void> startGuideFlow() async {
    bool isFirstLaunch = await GuideService.isFirstLaunch();
    bool isGuideCompleted = await GuideService.isGuideCompleted();
    
    if (isFirstLaunch && !isGuideCompleted) {
      isShowingGuide.value = true;
      await GuideService.setNotFirstLaunch();
    }
  }
  
  /// 触发 IndexPage 引导
  void triggerIndexGuide() {
    shouldShowIndexGuide.value = true;
    Get.log('🎯 触发 IndexPage 引导');
  }
  
  /// 触发 MapPage 引导
  void triggerMapGuide() {
    shouldShowMapGuide.value = true;
    Get.log('🎯 触发 MapPage 引导');
  }
  
  /// 触发 MessagePage 引导
  void triggerMessageGuide() {
    shouldShowMessageGuide.value = true;
    Get.log('🎯 触发 MessagePage 引导');
  }
  
  /// 触发 MinePage 引导
  void triggerMineGuide() {
    shouldShowMineGuide.value = true;
    Get.log('🎯 触发 MinePage 引导');
  }
  
  /// 重置 IndexPage 引导触发器
  void resetIndexGuideTrigger() {
    shouldShowIndexGuide.value = false;
  }
  
  /// 重置 MapPage 引导触发器
  void resetMapGuideTrigger() {
    shouldShowMapGuide.value = false;
  }
  
  /// 重置 MessagePage 引导触发器
  void resetMessageGuideTrigger() {
    shouldShowMessageGuide.value = false;
  }
  
  /// 重置 MinePage 引导触发器
  void resetMineGuideTrigger() {
    shouldShowMineGuide.value = false;
  }

  /// 完成所有引导
  Future<void> completeAllGuides() async {
    await GuideService.setGuideCompleted();
    isShowingGuide.value = false;
    currentGuideStep.value = 0;
  }
}

